package com.example.hotel_lxy.ui.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.example.hotel_lxy.R;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.EventBusBean;
import com.example.hotel_lxy.bean.ZeroSpSourceBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.activity.LoginActivity;
import com.example.hotel_lxy.ui.activity.ReserveActivity;
import com.example.hotel_lxy.ui.dialog.DataSelectionDialog;
import com.example.hotel_lxy.ui.main.CalendarActivity;
import com.example.hotel_lxy.ui.main.CalendarOrderActivity;
import com.example.hotel_lxy.utils.JurisdictionUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.ysxsoft.common_base.base.BaseFragment;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/***
 *
 * 订单
 *
 */
public class FragmentOrder extends BaseFragment {
    @BindView(R.id.rb_pending)
    RadioButton rbPending;
    @BindView(R.id.rb_all)
    RadioButton rbAll;
    @BindView(R.id.rb_order)
    RadioGroup rbOrder;
    @BindView(R.id.line_date)
    LinearLayout lineDate;

    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.rb1)
    RadioButton rb1;
    @BindView(R.id.rb2)
    RadioButton rb2;
    @BindView(R.id.text_start_time)
    TextView textStartTime;
    @BindView(R.id.time_end_time)
    TextView timeEndTime;
    @BindView(R.id.text_sp)
    TextView textSp;
    @BindView(R.id.fl_layout)
    FrameLayout flLayout;
    int order_type = 1;
    List<ZeroSpSourceBean.DataBean.ListBean> list;
    @BindView(R.id.text_sp_all)
    TextView textSpAll;
    @BindView(R.id.line_all)
    LinearLayout lineAll;
    @BindView(R.id.line_pending)
    LinearLayout linePending;
    private String director_id = "";
    private int position = 0;
    private Fragment tempFragment;
    boolean sayall;
    //fragment集合
    private List<BaseFragment> fragments = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.fragment_order_activity;
    }

    @Override
    protected void doWork(View view) {
        sayall = JurisdictionUtils.getSayall(getContext());
//        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        Date date = new Date(System.currentTimeMillis());//获取当前时间
//        String currentDate = simpleDateFormat.format(date);
//        textStartTime.setText(currentDate);
//        timeEndTime.setText(currentDate);
        String string = SPUtils.get(getContext(), "id", "").toString();
        director_id = string + "";
        //客户经理
        showDataView();
        fragments.add(new FragmentPending());//待处理
        fragments.add(new FragmentWhole());//全部

        BaseFragment baseFragment = getFragment(position);
        /**
         * 第一个参数: 上次显示的Fragment
         * 第二个参数: 当前正要显示的Fragment
         */
        switchFragment(tempFragment, baseFragment, position);

        rbOrder.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_pending:
                        order_type = 1;
                        lineAll.setVisibility(View.GONE);

                        linePending.setVisibility(View.VISIBLE);
                        rbOrder.setBackgroundDrawable(getResources().getDrawable(R.mipmap.icon_order_unprocessed));

                        BaseFragment baseFragment = getFragment(0);
                        /**
                         * 第一个参数: 上次显示的Fragment
                         * 第二个参数: 当前正要显示的Fragment
                         */
                        switchFragment(tempFragment, baseFragment, 0);
                        break;
                    case R.id.rb_all:
                        order_type = 2;
                        rbOrder.setBackgroundDrawable(getResources().getDrawable(R.mipmap.icon_order_all));
                        lineAll.setVisibility(View.VISIBLE);
                        linePending.setVisibility(View.GONE);
                        BaseFragment baseFragment1 = getFragment(1);
                        /**
                         * 第一个参数: 上次显示的Fragment
                         * 第二个参数: 当前正要显示的Fragment
                         */
                        switchFragment(tempFragment, baseFragment1, 1);
                        break;
                }
            }
        });
        if(!sayall){
            textSpAll.setTextColor(getContext().getResources().getColor(R.color.color_333333));
        }else{
            textSpAll.setTextColor(getContext().getResources().getColor(R.color.color_416DF9));
        }
    }

    private void showDataView() {
        OkHttpUtils.post()
                .url(Api.POST_ZERO_VIEW)
                .addHeader("flag", SPUtils.get(getContext(), "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户经理onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "客户经理onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(getContext(),"token","");
                            Intent intent = new Intent(getContext(), LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        ZeroSpSourceBean zeroSpSourceBean = JsonUtils.parseByGson(response, ZeroSpSourceBean.class);
                        String string = SPUtils.get(getContext(), "id", "").toString();

                        if (beanBean.getCode().equals("0")) {
                            list = zeroSpSourceBean.getData().getList();
                            if (list.size() != 0) {
                                for (int i = 0; i < list.size(); i++) {
                                    if(string.equals(""+list.get(i).getId())){

                                        textSp.setText("" + list.get(i).getUsername());
                                        textSpAll.setText("" + list.get(i).getUsername());
                                        EventBusBean eventBusBean = new EventBusBean();
                                        eventBusBean.setDid(director_id);
                                        if (order_type == 1) {
                                            eventBusBean.setType(7);
                                        } else {
                                            eventBusBean.setType(8);
                                        }
                                        EventBus.getDefault().post(eventBusBean); //普通事件发布
                                        return;
                                    }

                                }

                            }
                        }
                    }
                });
    }

    @OnClick({ R.id.text_sp,R.id.text_sp_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_sp:
                if(!sayall){
                    ToastUtils.longToast(getContext(),"当前账号没有操作权限哦");
                    return;
                }
                DataSelectionDialog.show(getContext(), null, Api.POST_ZERO_VIEW).setListener(new DataSelectionDialog.OnDialogClickListener() {
                    @Override
                    public void onPositiveClick(String id, String name) {
                        director_id = id + "";
                        textSp.setText("" + name);
                        EventBusBean eventBusBean = new EventBusBean();
                        eventBusBean.setDid(id);
                        eventBusBean.setName(name);
                        eventBusBean.setType(7);
                        EventBus.getDefault().post(eventBusBean); //普通事件发布
                    }
                });
                break;
            case R.id.text_sp_all:
                if(!sayall){
                    ToastUtils.longToast(getContext(),"当前账号没有操作权限哦");
                    return;
                }
                DataSelectionDialog.show(getContext(), null, Api.POST_ZERO_VIEW).setListener(new DataSelectionDialog.OnDialogClickListener() {
                    @Override
                    public void onPositiveClick(String id, String name) {
                        director_id = id + "";
                        textSpAll.setText("" + name);
                        EventBusBean eventBusBean = new EventBusBean();
                        eventBusBean.setDid(id);
                        eventBusBean.setName(name);
                        eventBusBean.setType(8);
                        EventBus.getDefault().post(eventBusBean); //普通事件发布
                    }
                });
                break;
        }
    }

    // 普通事件的处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(EventBusBean carrier) {
        if (carrier != null) {
            textStartTime.setText("" + carrier.getStarttime().replace("-", "-"));
            timeEndTime.setText("" + carrier.getStarttime().replace("-", "-"));
            EventBusBean eventBusBean = new EventBusBean();
            eventBusBean.setStarttime(textStartTime.getText().toString().replace("-", "-"));
            eventBusBean.setEndtime(timeEndTime.getText().toString().replace("-", "-"));
            eventBusBean.setType(6);
            EventBus.getDefault().post(eventBusBean); //普通事件发布

        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      //  EventBus.getDefault().register(this);  //事件的注册
    }

//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        if (hidden) {
//            EventBus.getDefault().unregister(this); //解除注册
//        } else {
//            EventBus.getDefault().register(this);  //事件的注册
//            //客户经理
//            showDataView();
//        }
//    }

    /**
     * 根据位置得到对应的 Fragment
     *
     * @param position
     * @return
     */
    private BaseFragment getFragment(int position) {
        if (fragments != null && fragments.size() > 0) {
            BaseFragment baseFragment = fragments.get(position);
            return baseFragment;
        }
        return null;
    }

    /**
     * 切换Fragment
     *
     * @param fragment
     * @param nextFragment
     */
    private void switchFragment(Fragment fragment, BaseFragment nextFragment, int position) {
        if (tempFragment != nextFragment) {
            tempFragment = nextFragment;
            if (nextFragment != null) {
                FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                //判断nextFragment是否添加成功
                if (!nextFragment.isAdded()) {
                    //隐藏当前的Fragment
                    if (fragment != null) {
                        transaction.hide(fragment);
                    }
                    //添加Fragment
                    transaction.add(R.id.fl_layout, nextFragment).commit();
                    if (position == 1) {
                        ((FragmentWhole) nextFragment).setRadioGroup(radioGroup);
                        ((FragmentWhole) nextFragment).setTextStartTime(textStartTime);
                        ((FragmentWhole) nextFragment).setTimeEndTime(timeEndTime);
                    }
                } else {
                    //隐藏当前Fragment
                    if (fragment != null) {
                        transaction.hide(fragment);
                    }
                    transaction.show(nextFragment).commit();
                }
            }
        }
    }

}